【问题标题】:how to enable v-model binding when building a custom components from other custom components从其他自定义组件构建自定义组件时如何启用 v-model 绑定
【发布时间】:2019-08-15 21:58:38
【问题描述】:

我能够从 <input /> 构建一个简单的文本框组件并正确设置 v-model 绑定。

我正在尝试对自定义组件做同样的事情:来自 vuesaxvs-input

以下模式无法按预期工作:

<template>
  <div>
    <vs-input type="text" v-model="value" @input="text_changed($event)" />
    <!-- <input type="text" :value="value" @input="$emit('input', $event.target.value)" /> -->
  </div>
</template>

<script>
export default {
  name: 'TestField',
  props: {
    value: {
      type: String,
      default: ''
    }
  },
  data() {
    return {}
  },
  methods: {
    text_changed(val) {
      console.log(val)
      // this.$emit('input', val)
    }
  }
}
</script>

在从其他自定义组件构建自定义组件时,我们应该注意什么以使 v-model 绑定正常工作?

【问题讨论】:

  • 在哪些方面表现不如预期?
  • 与常规输入框,v-model绑定有效。在 vs-input 中,我无法使用相同的代码模式让 v-model 绑定工作
  • 你能告诉我下面的代码工作正常吗?
  • @PALLAMOLLASAI 没有。给出错误Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value. Prop being mutated: "test"
  • 能否请您检查一下此链接。 stackoverflow.com/questions/51954716/…

标签: vue.js vue-component v-model


【解决方案1】:

以下代码可能会对您有所帮助。(示例代码在 codepen 中尝试)

updating props inside a child component

//html
<script src="https://unpkg.com/vue"></script>

<div id="app">
  <p>{{ message }}</p>
  <input type="text" :value="test" @change="abc">
  {{ test }}
</div>

//VUE CODE

new Vue({
   el: '#app',
   data: {
     message: 'Hello Vue.js!',
      },
   props:{
     test:{
        type:String,
        default:''
     } 
   },
  methods:{
     abc:function(event){
      //console.log("abc");
      console.log(event.target.value);
      this.test=event.target.value;
    }
   }
  })

【讨论】:

    【解决方案2】:

    我更喜欢将propscomputed 联系起来:

    <template>
      <div>
        <vs-input type="text" v-model="cValue" />
      </div>
    </template>
    
    <script>
    export default {
      name: 'TestField',
      props: {
        value: {
          type: String,
          default: ''
        }
      },
      data() {
        return {}
      },
      computed: {
        cValue: {
          get: function(){
            return this.value;
          },
          set: function(val){
    
             // do w/e
             this.$emit('input', val)
          }
        }
      }
    }
    </script>
    

    Computed Setter

    【讨论】:

      猜你喜欢
      • 2019-06-14
      • 2017-11-07
      • 2022-01-06
      • 2020-09-24
      • 2018-10-03
      • 1970-01-01
      • 2021-08-25
      • 2020-09-26
      • 1970-01-01
      相关资源
      最近更新 更多