所以我有这个代码:
<input id="txtboxid" type="text" v-model="full_name"><label for="txtboxid">中间名 *</label>而且我有很多具有不同 ID 和型号的文件,而且我的 html 文件看起来很大.有没有办法在 vuejs 中缩短它?就像只有一行一样,它会有那些?任何帮助将不胜感激.
解决方案正如您在问题中指出的那样,您可以创建可重用的 components 在 Vue.js 中,用于一次又一次地使用相同的 HTML 模板.你可以从你的代码创建一个简单的 vue component 如下:
Vueponent('child', {模板: '\<div class="input-field col s12 m6 l6">\<input :id="id" type="text" v-model="value">\<label for="txtboxid">中间名 *</label>\\',道具: ["id", "value"],手表: {值:函数(新值){this.$emit('input', newVal)}}})
它可以在您的 HTML 中使用,只需使用一行即可:
请在此处检查工作中的提琴手.
在上面的代码中我使用了watch,你也可以使用事件处理程序更改@change 要在父级中更新 full_name,演示 here.
一些解释:
我在这里使用 v-model.<input v-model="something"> 在这里,它本质上是语法糖:
您可以使用它来创建组件并在 v-model 中发送您的变量,并在组件中将其作为 道具.
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. Is there a way to make it shorter in 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. You can create a simple vue component from your code as following:
Vueponent('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:
<child v-model="full_name" id="24"></child>Please check working fiddler here.
In the above code I am using watch, you can also use event handler on change @change to get the full_name updated in the parent, demo here.
Some Explanation:
I am using v-model here. <input v-model="something"> here, which is essentially syntactic sugar for:
<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.
更多推荐
如何在 Vue 中为 html 代码创建组件?
发布评论