如何在 Vue 中为 html 代码创建组件?

编程入门 行业动态 更新时间:2024-10-25 19:35:59
本文介绍了如何在 Vue 中为 html 代码创建组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

所以我有这个代码:

<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 代码创建组件?

本文发布于:2023-06-04 19:07:02,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/503327.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:中为   组件   代码   如何在   Vue

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!