我的代码是按照老师写的,先用props接收父组件的值,然后在data里面重新定义了一个值,修改了一个组件里面的值之后,另外一组件里面也会跟着变。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="vue.min.js"></script>
</head>
<body>
<div id="app">
{{msg}}
<counter :count="obj"></counter>
<counter2 :count="obj"></counter2>
</div>
<script>
var counter = {
props:['count'],
data : function () {
return {
user:this.count
}
},
template : "<div @click='handleClick'>{{user}}</div>",
methods : {
handleClick:function () {
// this.count ++;
console.log('counter');
this.user.name ='counter';
}
}
};
var counter2 = {
props:['count'],
data : function () {
return {
user:this.count
}
},
template : "<div @click='handleClick2'>{{user}}</div>",
methods : {
handleClick2:function () {
// this.count ++;
console.log('counter2');
this.name.name ='counter2';
}
}
};
var vm = new Vue(
{
el: '#app',
data: {
msg: "hello world",
obj:{"name":"nhy"}
},
components: {
counter,
counter2,
}
}
);
</script>
</body>
</html>
课程紧跟Vue3版本迭代,企业主流版本Vue2+Vue3全掌握
了解课程