美文网首页
vue v-model 在子组件中修改父组件的数据,前提被修改的

vue v-model 在子组件中修改父组件的数据,前提被修改的

作者: 八妹sss | 来源:发表于2020-10-23 15:36 被阅读0次

1、当数据是基础类型时,例如String,报警告

父组件

<template>
  <div class="home">
    <HelloWorld msg="Welcome to Your Vue.js App" :src="src"/>
  </div>
</template>

<script>
// @ is an alias to /src
import HelloWorld from '@/components/HelloWorld.vue'

export default {
  name: 'Home',
  data () {
    return  {
      src: 'http://static.oss.yuemia.com/202010231521160099.jpeg'
    }
  },
  components: {
    HelloWorld
  }
}
</script>

子组件

<template>
  <div class="hello">
    <h1 @click="handleChange()">{{ msg }}</h1>
    <img :src="src" alt="">
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  props: {
    msg: String,
    src: String // 基础类型
  },
  methods: {
    handleChange () {
      this.src = 'http://static.oss.yuemia.com/202007081458270399.png'
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="stylus">
.hello
  width 100%
  img 
   max-height 400px
</style>

警告:


image.png

2、当数据是非基础类型时,例如Object,正常

父组件

<template>
  <div class="home">
    <HelloWorld msg="Welcome to Your Vue.js App" :info="info"/>
  </div>
</template>

<script>
// @ is an alias to /src
import HelloWorld from '@/components/HelloWorld.vue'

export default {
  name: 'Home',
  data () {
    return  {
      info: {
        src: 'http://static.oss.yuemia.com/202010231521160099.jpeg'
      }
    }
  },
  components: {
    HelloWorld
  }
}
</script>

子组件

<template>
  <div class="hello">
    <h1 @click="handleChange()">{{ msg }}</h1>
    <img :src="info.src" alt="">
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  props: {
    msg: String,
    info: Object // 非基础类型
  },
  methods: {
    handleChange () {
      this.info.src = 'http://static.oss.yuemia.com/202007081458270399.png'
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="stylus">
.hello
  width 100%
  img 
   max-height 400px
</style>

相关文章

网友评论

      本文标题:vue v-model 在子组件中修改父组件的数据,前提被修改的

      本文链接:https://www.haomeiwen.com/subject/dxvvmktx.html