props

102 阅读1分钟

目的:想在子组件中改变父组件通过props传递过来的值,父组件中也跟着变化,那么看下面:

props,.sync修饰符和$emit 结合使用:

上代码:

父组件:

<template>
<div>
    <div class="home">
      <!-- 父组件中使用传递过去的值,方便观察变化 -->
      <div>{{name}}</div>
      <HelloWorld :childname.sync='name' @childclick='getchild($event)'/>
    </div>
  </div>
</template>
<script>
import HelloWorld from '@/components/HelloWorld.vue'
export default {
  components: {
    HelloWorld
  },
  data(){
    return{
      name:'zhangsan'
    }
  },
  methods:{
    getchild(res){
      // 接收子组件传递过来的值
      console.log(res);
    }
  }
}
</script>

子组件:

<template>
  <div class="hello">
    <button @click="$emit('childclick',name)">给父组件传值</button>
    <button @click="change">改变父组件传递的值</button>
  </div>
</template>
<script>
export default {
  props:['childname'],
 data(){
   return{
     name:'lisi',
   }
 },
 methods:{
   change(){
    //此处将传递过来的值改为‘lisi’,父组件中的name也跟着变化
     this.$emit('update:childname',this.name)
     console.log(this.childname);
   }
 },
}
</script>