vue中的单项数据流

在VUE中,数据从父组件流向(传递)给子组件,只能单向绑定,在子组件内部不应该修改父组件传递过来的数据。
如果必须修改子组件中接收的数据,可以:
1. 作为data中局部数据,进行改动
2. 作为子组件中的computed树属性

例如,下面例子中,虽然可以实现count加1,但是会报错。

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
    <title>组件</title>
    <style>
    </style>
    <script src="https://unpkg.com/vue/dist/vue.js"></script>
</head>
<body>
    <div id="app">
        <custom-component v-bind:message="count"></custom-component>
    </div>
    <script>
        Vue.component("custom-component",{
            props: ['message'],
            template:`
                <div>
                    <h2>自定义组件</h2>
                    {{message}}
                    <input type="button" value="加一" v-on:click = "changeMssage" />
                </div> `,
            methods: {
                changeMssage(){
                    this.message++;
                }
            }
        })

        new Vue({
            el:"#app",
            data(){
                return {count: 0}
            }
        })
    </script>
</body>
</html>

需要对上面进行改动如下:

<script>
	Vue.component("custom-component",{
		props: ['message'],
		data(){
			return {
				plus: this.message   // data必须以函数形式返回数据
			}
		},
		template:`
			<div>
				<h2>自定义组件</h2>
				{{plus}}
				<input type="button" value="加一" v-on:click = "changeMssage" />
			</div> `,
		methods: {
			changeMssage(){
				this.plus++;
			}
		}
	})

	new Vue({
		el:"#app",
		data(){
			return {count: 0}
		}
	})
</script>
原文地址:https://www.cnblogs.com/cckui/p/7492457.html