单项数据流 示例

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>单项数据流</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="js/vue.js"></script>
</head>
<body>
<div id="container">
<h2>父组件:{{name}}</h2>
<input type="text" v-model="name">
<h2>父组件:{{user.age}}</h2><!--方式3-->
<hr>
<!--<my-hello :name="name"></my-hello>--><!-- 方式2-->
<!--<my-hello :name.sync="name"></my-hello>--><!-- 方式2-->
<my-hello :name.sync="name" :user="user"></my-hello><!-- 方式3-->

</div>

<template id="hello">
<div>
<!--<h2>子组件:{{userName}}</h2>--><!-- 方式1-->
<!-- <h2>子组件:{{name}}</h2> --><!--方式2-->
<h2>子组件:{{user.age}}</h2><!--方式3-->
<button @click="change">修改数据</button>
</div>
</template>

<script>

//配置是否允许vue-devtools检查代码,方便调试,生产环境中需要设置为false
Vue.config.devtools=false;
Vue.config.productionTip=false;//阻止vue启动时生成生产消息

new Vue({
el:"#container",
data:{
name:"tom",
user:{
name:"张三",
age:12
}
},
components:{
'my-hello':{
template:'#hello',
props:['name','user'],
data(){
return {
userName:this.name//方式1:将数据存入另一个变量中在操作
}
},
methods:{
change(){
// this.name="小零" :不允许子组件直接修改父组件中的数据,报错
// this.userName="小零"//方式1:
// this.$emit('update:name','小零')//方式2
this.user.age=18
}
}
}
}

})
</script>
</body>
</html>

猜你喜欢

转载自www.cnblogs.com/yuezhen/p/10408194.html
今日推荐