前言
vue 组件有很多种写法,最常见的是单文件组件(.vue)的三段式,但除此之外还有其他的书写方式,了解更多对我们后续的开发有很大的帮助。本文介绍 vue 组件全部的写法。
vue 两个版本的区别详见 Vue 的两个版本
template 写法
template 的写法依赖 vue-template-compiler编译器。
使用语法如下:
Vue.component("cp-test", {template: `<div>{{hi}}<p>其他内容</p></div>`,data() {return {hi: "我是组件"}}})
render 函数写法
render 函数不依赖任何编译器,是最原始的写法。其中 h 是 createElement的简写别名。
使用语法如下:
Vue.component("cp-test", {render(h) {return h("div", [this.hi,h("p", ["其他内容"])])},data() {return {hi: "我是组件"}}})
jsx 写法
jsx 写法是在 render 函数写法的基础上做的延伸,依赖 jsx 编译器,即 babel,具体配置详见 babel jsx vue2。
使用语法如下:
Vue.component("cp-test", {render(h) {return (<div>{{hi}}<p>其他内容</p></div>)},data() {return {hi: "我是组件"}}})
单文件写法
单文件写法依赖 vue-loader编译器。
使用语法如下:
// test.vue<template><div>{{ hi }}<p>其他内容</p></div></template><script>export default {data() {return {hi: "我是组件"}}}</script><style>/* 样式 */</style>
