Vue组件间传值 和 访问
1、根组件向子组件传值 :使用props属性
<html>
<body>
<script src="vue.js"></script>
<template id="myt">
<div>
<p>{{name}}</p>
<p>{{pwd}}</p>
<p>{{cmsg}}</p>
</div>
</template>
<div id="app">
<cpn :person="p" :cmsg="msg"></cpn>
</div>
<script>
Vue.component("cpn", {
template: "#myt",
props: {
person: Person,
cmsg: String
}
})
//定义一个Person对象
function Person(m, p) {
name = m;
pwd = p;
}
const app = new Vue({
el: "#app",
data: {
msg: "hello",
p: new Person("张三", 123)
},
})
</script>
</body>
</html>
props可以是数组形式表示 :props:['prop1','prop2','prop3'] ,也可以对象形式props:{prop1:String,prop2:Array,prop3:Object} 。对象形式更加灵活。
注意:如果子组件属性使用驼峰命名,在组件上写属性时把大写换成小写并在前面加-号。要么全写成小写
2、子组件向父组件传值:使用this.$emit()
<html>
<body>
<script src="vue.js"></script>
<template id="myt">
<div>
<ul>
<li v-for="item in clist">
<button v-on:click="cbtnClick(item)">{{item.name}}</button>
</li>
</ul>
</div>
</template>
<div id="app">
<cpn :clist="list" @clickbutton="childclickbutton"></cpn>
<h3>选择对象:{{curPerson}}</h3>
</div>
<script>
Vue.component("cpn", {
template: "#myt",
props:['clist'],
methods: {
cbtnClick(item) {
this.$emit("clickbutton",item);
}
}
})
const app = new Vue({
el: "#app",
data: {
curPerson: {},
list: [
{
id: 1,
name: '张三'
},
{
id: 2,
name: '李四'
},
{
id: 3,
name: '王五'
},
],
},
methods: {
childclickbutton(item) {
this.curPerson = item;
}
}
})
</script>
</body>
</html>
3、父访问子组件的方法:this.$children ,this.$refs(常用)
<html>
<body>
<script src="vue.js"></script>
<template id="myt">
<div>
<h2>{{info}}</h2>
</div>
</template>
<div id="app">
<cpn ref="child"></cpn>
<button v-on:click="btnclick">访问</button>
<h3>{{result}}</h3>
</div>
<script>
Vue.component("cpn", {
template: '#myt',
data() {
return {
info:"我是子组件属性"
}
},
methods: {
getInfo() {
return this.info;
}
}
})
const app = new Vue({
el: "#app",
data: {
result: ""
},
methods: {
btnclick() {
this.result = this.$refs.child.getInfo();
}
}
})
</script>
</body>
</html>
4、子访问父组件 :this.$parents (父组件) ,this.$root (根组件)
<html>
<body>
<script src="vue.js"></script>
<template id="myt">
<div>
<button v-on:click="btnclick">访问父</button>
<h2>{{msg}}</h2>
</div>
</template>
<div id="app">
<cpn></cpn>
</div>
<script>
Vue.component("cpn", {
template: '#myt',
data() {
return {
msg:""
}
},
methods: {
btnclick() {
this.msg = this.$root.msg;
}
}
})
const app = new Vue({
el: "#app",
data: {
msg: "我是父组件中的值"
},
})
</script>
</body>
</html>
浙公网安备 33010602011771号