60分钟组件快速入门(上篇)(3)

<!DOCTYPE html> <html> <body> <div> <my-component></my-component> </div> <script type="text/x-template"> <div>This is a component!</div> </script> </body> <script src="https://www.jb51.net/js/vue.js"></script> <script> Vue.component('my-component',{ template: '#myComponent' }) new Vue({ el: '#app' }) </script> </html>

template选项现在不再是HTML元素,而是一个id,Vue.js根据这个id查找对应的元素,然后将这个元素内的HTML作为模板进行编译。

60分钟组件快速入门(上篇)

注意:使用<script>标签时,type指定为text/x-template,意在告诉浏览器这不是一段js脚本,浏览器在解析HTML文档时会忽略<script>标签内定义的内容。

使用<template>标签

如果使用<template>标签,则不需要指定type属性。

<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> </head> <body> <div> <my-component></my-component> </div> <template> <div>This is a component!</div> </template> </body> <script src="https://www.jb51.net/js/vue.js"></script> <script> Vue.component('my-component',{ template: '#myComponent' }) new Vue({ el: '#app' }) </script> </html>

在理解了组件的创建和注册过程后,我建议使用<script>或<template>标签来定义组件的HTML模板。

这使得HTML代码和JavaScript代码是分离的,便于阅读和维护。

另外,在Vue.js中,可创建.vue后缀的文件,在.vue文件中定义组件,这个内容我会在后面的文章介绍。

组件的el和data选项

传入Vue构造器的多数选项也可以用在 Vue.extend() 或Vue.component()中,不过有两个特例: data 和el。
Vue.js规定:在定义组件的选项时,data和el选项必须使用函数。

下面的代码在执行时,浏览器会提出一个错误

Vue.component('my-component', { data: { a: 1 } })

60分钟组件快速入门(上篇)

另外,如果data选项指向某个对象,这意味着所有的组件实例共用一个data。

我们应当使用一个函数作为 data 选项,让这个函数返回一个新对象:

Vue.component('my-component', { data: function(){ return {a : 1} } })

使用props

组件实例的作用域是孤立的。这意味着不能并且不应该在子组件的模板内直接引用父组件的数据。可以使用 props 把数据传给子组件。

props基础示例

下面的代码定义了一个子组件my-component,在Vue实例中定义了data选项。

var vm = new Vue({ el: '#app', data: { name: 'keepfool', age: 28 }, components: { 'my-component': { template: '#myComponent', props: ['myName', 'myAge'] } } })

为了便于理解,你可以将这个Vue实例看作my-component的父组件。

如果我们想使父组件的数据,则必须先在子组件中定义props属性,也就是props: ['myName', 'myAge']这行代码。

定义子组件的HTML模板:

<template> <table> <tr> <th colspan="2"> 子组件数据 </th> </tr> <tr> <td>my name</td> <td>{{ myName }}</td> </tr> <tr> <td>my age</td> <td>{{ myAge }}</td> </tr> </table> </template>

将父组件数据通过已定义好的props属性传递给子组件:

<div> <my-component v-bind:my-name="name" v-bind:my-age="age"></my-component> </div>

注意:在子组件中定义prop时,使用了camelCase命名法。由于HTML特性不区分大小写,camelCase的prop用于特性时,需要转为 kebab-case(短横线隔开)。例如,在prop中定义的myName,在用作特性时需要转换为my-name。

这段程序的运行结果如下:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wwfpfs.html