其他分享
首页 > 其他分享> > vue子组件改变父组件值--写法2

vue子组件改变父组件值--写法2

作者:互联网

1、父:要点

  1. 正常父传子:msg="oldValue"
  2. 正常子接父@iClick="yClick"
<template>
  <div id="app">
    <HelloWorld @iClick="yClick" :msg="oldValue"/>
  </div>
</template>

<script>
import HelloWorld from './components/HelloWorld.vue'

export default {
  name: 'App',
  components: {
    HelloWorld
  },
  methods: {
    yClick (value) {
      this.oldValue = value
    }
  },
  data () {
    return {
      oldValue: 'oldValue'
    }
  }
}
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

 

2、子:要点

  1. watch监听属性
    childMsg 
  2. 正常子传父
    this.$emit('iClick', newValue)
<template>
  <div class="hello">
    <h1>msg-props==={{ msg }}</h1>
    <h1>childMsg-data==={{ childMsg }}</h1>
    <input type="text" v-model="childMsg" />
<!--    <input type="text" :value="childMsg" @input="changeMsg" />-->
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  props: {
    msg: {
      type: String
    }
  },
  data () {
    return {
      childMsg: this.msg
    }
  },
  methods: {

  },
  watch: {
    childMsg (newValue) {
      this.$emit('iClick', newValue)
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h3 {
  margin: 40px 0 0;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #42b983;
}
</style>

 

标签:vue,--,childMsg,HelloWorld,msg,oldValue,iClick,组件,font
来源: https://www.cnblogs.com/yangh-ai/p/14983112.html