如何在 Vue 中为 html 代码创建组件?
How to create a component for a html code in Vue?
所以我有这个代码:
<div class="input-field col s12 m6 l6">
<input id="txtboxid" type="text" v-model="full_name">
<label for="txtboxid">Middle Name *</label>
</div>
而且我有很多具有不同 ID 和型号的文件,而且我的 html 文件看起来很大。有没有办法让它在 vuejs 中变短?就像只有一条线,它会有那些?任何帮助将不胜感激。
正如您在问题中指出的那样,您可以从代码中创建 re-usable components in Vue.js
, for using the same HTML template again and again. You can create a simple vue component,如下所示:
Vue.component('child', {
template: '\
<div class="input-field col s12 m6 l6"> \
<input :id="id" type="text" v-model="value"> \
<label for="txtboxid">Middle Name *</label> \
</div> \
',
props: [
"id", "value"],
watch: {
value: function(newVal){
this.$emit('input', newVal)
}
}
})
它可以在你的 HTML 中使用,只需使用一行:
<child v-model="full_name" id="24"></child>
请检查工作提琴手 here。
在上面的代码中我使用了watch, you can also use event handler on change @change
to get the full_name
updated in the parent, demo here。
一些解释:
我这里用的是v-model。 <input v-model="something">
这里,本质上是语法糖:
<input v-bind:value="something" v-on:input="something = $event.target.value">
您可以使用它来创建组件并在 v-model
中发送您的变量并在组件中接受它作为 props。
所以我有这个代码:
<div class="input-field col s12 m6 l6">
<input id="txtboxid" type="text" v-model="full_name">
<label for="txtboxid">Middle Name *</label>
</div>
而且我有很多具有不同 ID 和型号的文件,而且我的 html 文件看起来很大。有没有办法让它在 vuejs 中变短?就像只有一条线,它会有那些?任何帮助将不胜感激。
正如您在问题中指出的那样,您可以从代码中创建 re-usable components in Vue.js
, for using the same HTML template again and again. You can create a simple vue component,如下所示:
Vue.component('child', {
template: '\
<div class="input-field col s12 m6 l6"> \
<input :id="id" type="text" v-model="value"> \
<label for="txtboxid">Middle Name *</label> \
</div> \
',
props: [
"id", "value"],
watch: {
value: function(newVal){
this.$emit('input', newVal)
}
}
})
它可以在你的 HTML 中使用,只需使用一行:
<child v-model="full_name" id="24"></child>
请检查工作提琴手 here。
在上面的代码中我使用了watch, you can also use event handler on change @change
to get the full_name
updated in the parent, demo here。
一些解释:
我这里用的是v-model。 <input v-model="something">
这里,本质上是语法糖:
<input v-bind:value="something" v-on:input="something = $event.target.value">
您可以使用它来创建组件并在 v-model
中发送您的变量并在组件中接受它作为 props。