1. 程式人生 > 其它 >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>