Vue2之父子组件传值与watch监听案例

Vue2之父子组件传值与watch监听案例

文章目录

  • Vue2之父子组件传值与watch监听案例
  • 1. 父子组件传值
    • 1. props
      • 1. 父组件
      • 2. 子组件props与watch
      • 3. 子组件props与watch(立即监听)

1. 父子组件传值

1. props

props传值是单向的,即值由父组件传递,子组件只负责显示,但是子组件不能改变其值,如果值要随着父组件的改变而改变,则加入wach监听

1. 父组件

... 

...

2. 子组件props与watch

<template>
  <div>
   <img :src="imgPath">
  </div>
</template>
<script lang="ts">
export default defineComponent({
  props:{
    modelScsPath:{
      type:String
    }
  },
  name: "SubComponent",
  components: {
    //...
  },
  watch: {
    //监听文件url改变时重新赋值
    modelScsPath(newVal, oldVal) {
        //console.log('imgPath changed from', oldVal, 'to', newVal);
        this.imgPath = newVal
      }
  },
  data() {
    return {
      imgPath: "../../assets/test.png",
  },
  methods: {
    // define you method
  },
});
</script>

3. 子组件props与watch(立即监听)

<template>
  <div>
   <img :src="imgPath">
  </div>
</template>
<script lang="ts">
export default defineComponent({
  props:{
    modelScsPath:{
      type:String
    }
  },
  name: "SubComponent",
  components: {
    //...
  },
  watch: {
    //监听模型文件url改变时重新赋值
    modelScsPath: {
      handler(newVal, oldVal) {
        //console.log('imgPath changed from', oldVal, 'to', newVal);
        this.imgPath = newVal
      },
      immediate: true
    },
  },
  data() {
    return {
      imgPath: "../../assets/test.png",
  },
  methods: {
    // define you method
  },
});
</script>

你可能感兴趣的:(vue2,javascript,vue.js,前端,typescript)