带有HTML的Vue.js自定义组件

问题描述 投票:0回答:1
我是Vue.js的新手(使用Nuxt.js),我想实现的目标是拥有一个Select组件,该组件可以在任何地方重用并且符合W3C。

[@ Jasmonate答案的帮助下,我设法创建了此组件,它正在运行。但是value属性在源代码中仍然可见,因此与W3C不兼容。也许问题出在项目的其他地方?!

父组件

<custom-select :options="options" v-model="selectedOption" ></custom-select> <span>Selected : {{ selectedOption }}</span> <script> data() { return { selectedOption: "A", options: [ { label: "One", value: "A" }, { label: "Two", value: "B" }, { label: "Three", value: "C" } ], }; } </script>

custom-select.vue

<template> <select :value="value" @input="clicked"> <option v-for="option in options" :key="option.label" :value="option.value" > {{ option.label }} </option> </select> </template> <script> export default { props: { value: { required: true }, options: { type: Array, required: true } }, methods: { clicked($event) { this.$emit("input", $event.target.value); } } }; </script>

我阅读了这些文档页面:

  • 并且还环顾了整个网络,以在自定义组件中找到v-model的示例,但这始终与输入标签有关。我发现的关于带有v-model的自定义选择的唯一示例实际上不是选择标签,例如Vue Select插件或StackOverflow上的this thread
  • vue.js html-select nuxt.js w3c-validation v-model
    1个回答
    1
    投票
    v-model是语法糖。默认情况下,该值是一个名称为value的prop,并且每次发出事件input时它都会更改(双向绑定)。

    此外,v模型绑定在select元素上,而不是option上。

    您的代码可以这样修改:

    <template> <select :value="value" @input="clicked"> <option v-for="option in options" :key="option.label" :value="option.value" > {{ option.label }} </option> </select> </template> <script> export default { props: { value: { required: true }, options: { type: Array, required: true } }, methods: { clicked($event) { this.$emit('input', $event.target.value); } } }; </script>

    此处的文档:https://vuejs.org/v2/guide/components.html#Using-v-model-on-Components

    您还可以更改v-model使用的道具名称和事件名称,请参阅:https://vuejs.org/v2/guide/components-custom-events.html#Customizing-Component-v-model

    © www.soinside.com 2019 - 2024. All rights reserved.