v-model for child component and v-model inside child component Vue

前端 未结 1 1100
滥情空心
滥情空心 2021-02-06 11:07

Is there a way to simplify this code?

The button should also change the localValue of the child.

1条回答
  •  眼角桃花
    2021-02-06 11:44

    If you avoid using v-model inside your custom form component, you really only need

    My Input: 
    localValue: {{ value }}

    No data, no watch, that's it.

    See https://vuejs.org/v2/guide/components.html#Using-v-model-on-Components


    If you really want something representing a value local to your component, the Vue docs favour using computed values over watchers (ref: https://vuejs.org/v2/guide/computed.html#Watchers).

    The idea here is to create a computed value with getter and setter to facilitate a simplified one-way data flow.

    Vue.component('my-input', {
      template: `
    My Input:
    localValue: {{ localValue }}
    `, props: ['value'], computed: { localValue: { get () { return this.value }, set (value) { this.$emit('input', value) } } } }) new Vue({ el: '#app', data: () => ({ parentValue: 'Inital value' }), methods: { change () { this.parentValue = 'Changed value' } } })
    
    

    parentValue: {{ parentValue }}

    0 讨论(0)
提交回复
热议问题