使用vue-cli构建完成后,HelloWorld为父组件,Test和Test2为子组件
一 父组件向子组件传值
HelloWorld.vue:
<template>
<div class="hello">
<h1>{{ msg }}</h1>
<test :name="name"></test> <!--使用子组件Test-->
<test2 :name="name"></test2> <!--使用子组件Test2-->
</div>
</template>
<script>
import Test from '@/components/Test'; //导入子组件Test
import Test2 from '@/components/Test2'; //导入子组件Test2
export default {
name: 'HelloWorld',
data () {
return {
msg: 'hello',
name:'world'
}
},
components:{ //导入子组件
'test':Test,
'test2':Test2
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>
Test.vue:
<template>
<div>
<p @click="change">{{name}}</p>
</div>
</template>
<script>
export default {
name: "Test",
props:{
name:{
type:String,
required:true
}
},
data(){
return {
}
},
methods:{
change:function () {
this.name='修改了的name'
}
}
}
</script>
这样就可以获取到父组件里的数据了,但是当触发change事件时虽然可以改变name值但是会报一个警告,类似:
Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value. Prop being mutated: "name"
大概意思就是:避免直接改变属性,因为每当父组件重新呈现时,该值都将被覆盖。相反,使用基于属性值的数据或计算属性。
可以在子组件里使用一个值去接受这个数据,绑定这个值就行了,这样警告就没有了
Test.vue:
<template>
<div>
<p @click="change">{{testName}}</p>
</div>
</template>
<script>
export default {
name: "Test",
props:{
name:{
type:String,
required:true
}
},
data(){
return {
testName:this.name,
}
},
methods:{
change:function () {
this.testName='修改了的name'
}
}
}
</script>
<style scoped>
</style>
二 子组件向父组件传值(事件传值)
Test.vue:
<template>
<div>
<p @click="changeTitle">子向父组件传值</p>
</div>
</template>
<script>
export default {
name: "User",
data(){
return {
}
},
methods:{
changeTitle:function () {
this.$emit('updateTitle','子向父组件传值')
}
}
}
</script>
<style scoped>
</style>
HelloWorld.vue:
<template>
<div class="hello">
<h1>{{ name }}</h1>
<user @updateTitle="changeTitle($event)" v-bind:name="name"></user> <!--使用子组件user-->
</div>
</template>
<script>
import User from '@/components/User'; //导入子组件User
export default {
name: 'HelloWorld',
data () {
return {
name:'父组件',
}
},
methods:{
changeTitle:function (name) {
this.name=name;
}
},
components:{ //导入子组件
'user':User
}
}
</script>
三 slot的使用
子组件:
<template>
<div>子组件
<slot></slot> <!--未命名的slot-->
<slot name="a"></slot> <!--已命名的slot-->
</div>
</template>
<script>
export default{
name : 'Test',
}
</script>
父组件:
<template>
<div>
<Test>
父组件 <!--未命名的slot传值-->
<div slot='a'>12312</div> <!--已命名的slot传值-->
</Test>
</div>
</template>
<script>
import Test from '@/components/Test';
export default {
components:{Test},
name:'Home',
}
如果子组件没有slot标签,父组件没办法向子组件里直接传值的。