簡體   English   中英

Vue JS - 帶有 v-model 的按鈕上的雙向數據綁定

[英]Vue JS - Two way data binding on a button with v-model

更高版本的 Vue JS 2 抱怨在按鈕上使用v-model 它顯示錯誤:

<button v-model="settings.primary_color">: v-model is not supported on this element type. If you are working with contenteditable, it's recommended to wrap a library dedicated for that purpose inside a custom component.

這是我的按鈕:

<button type="button" class="colorpicker" v-model="settings.primary_color" :data-color="settings.primary_color" :style="{'background-color' : settings.primary_color}"></button>

是否可以使用data-color屬性而不是輸入值來實現雙向數據綁定?

當然有可能,這是現代 JS 框架的目標。

錯誤說的是“按鈕”標簽上的綁定數據是不可能的。 原因是“按鈕”是一個原生的 html 元素。

因此,如果您想在按鈕上綁定數據,只需創建一個像“my-button”這樣的新組件,就可以實現 ti !

<my-button 
    class="colorpicker"
    :type="button"
    v-model="settings.primary_color" 
    :data-color="settings.primary_color" 
    :style="{'background-color' : settings.primary_color}"
></my-button>

通過更好地了解您的問題,我向您提出了這個解決方案

只需通過 input[type="color"] 更改您的按鈕

組件:

<template>
  <div>
    <input type="color" v-model="color"/>
    {{ color }}
  </div>
</template>

<script>
export default {
  name: "ColorPicker",
  data: () => ({
    color: "#000000",
  }),
};
</script>

因為我們現在有一個輸入,所以 v-model 是可能的

編輯:所以,繼續使用你的按鈕(我猜,你的顏色選擇器類很重要,因為你已經做了一些工作)

根據VueJs文檔,要創建自己的兩種數據綁定方式,您必須獲取道具“值”並在組件上發出信號“輸入”

(我只是做了一個 generateRandomColor() 函數來更快)

創建一個按鈕組件:

<template>
  <div>
    <button class="colorpicker" @click="triggered">Click me</button>
  </div>
</template>


<script>
export default {
  name: "ColorPicker",
  props: {
    value: String,
  },
  data: () => ({
    value_: "#000000",
  }),
  methods: {
    triggered: function () {
      this.value_ = this.getRandomColor();
      this.$emit("input", this.value_);
    },
    getRandomColor: function () {
      var letters = "0123456789ABCDEF";
      var color = "#";
      for (var i = 0; i < 6; i++) {
        color += letters[Math.floor(Math.random() * 16)];
      }
      return color;
    },
  },
};
</script>

然后,在你的父母中調用它:

<color-picker v-model="colors.primary"></color-picker>

對於您的使用,您只需更新自定義按鈕組件中的value_屬性,值將在父級中自動更新

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM