[英]How to create a component for a html code in Vue?
So I have this code:所以我有这个代码:
<div class="input-field col s12 m6 l6">
<input id="txtboxid" type="text" v-model="full_name">
<label for="txtboxid">Middle Name *</label>
</div>
And I have lots of those with different ID's and model's and my html file looks big.而且我有很多具有不同 ID 和型号的人,而且我的 html 文件看起来很大。 Is there a way to make it shorter in vuejs?有没有办法让它在 vuejs 中变短? Like just a single line and it will have those?就像只有一条线,它会有那些? Any help would be much appreciated.任何帮助将非常感激。
As you have pointed out in the question, itself, you can create re-usable components in Vue.js
, for using the same HTML template again and again.正如您在问题中指出的那样,您可以在Vue.js
中创建可重用的组件,以便一次又一次地使用相同的 HTML 模板。 You can create a simple vue component from your code as following:您可以从您的代码中创建一个简单的 vue组件,如下所示:
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)
}
}
})
and it can be used in your HTML just by using single line:它可以在您的 HTML 中使用,只需使用单行:
<child v-model="full_name" id="24"></child>
Please check working fiddler here .请在此处检查工作提琴手。
In the above code I am using watch , you can also useevent handler on change @change
to get the full_name
updated in the parent, demo here .在上面我使用watch的代码中,您还可以在 change @change
上使用事件处理程序来获取父级中的full_name
更新,demo here 。
Some Explanation:一些解释:
I am using v-model here.我在这里使用v-model 。 <input v-model="something">
here, which is essentially syntactic sugar for: <input v-model="something">
这里,本质上是语法糖:
<input v-bind:value="something" v-on:input="something = $event.target.value">
You can use this to create components and send your varaible in v-model
and accept it in the component as props .您可以使用它来创建组件并在v-model
中发送您的变量,并在组件中将其作为props接受。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.