Vue组件的定义方式

时间:2023-03-09 03:20:03
Vue组件的定义方式

1、使用template标签定义组件

 <!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<div id="app">
<my-component></my-component>
</div> <template id="myComponent">
<div>This is a component!</div>
</template>
</body>
<script src="js/vue.js"></script>
<script> Vue.component('my-component',{
template: '#myComponent'
}) new Vue({
el: '#app'
}) </script>
</html>
 这种方式可以将以template定义的组件放在当前页面中,也可以以单独的文件形式存在,然后再使用的页面中使用import引入即可。

2、使用script标签定义组件

 <!DOCTYPE html>
<html>
<body>
<div id="app">
<my-component></my-component>
</div> <-- 注意:使用<script>标签时,type指定为text/x-template,意在告诉浏览器这不是一段js脚本,浏览器在解析HTML文档时会忽略<script>标签内定义的内容。--> <script type="text/x-template" id="myComponent"> //type类型为 text/x-template; id为组件的名称。
<div>This is a component!</div>
</script>
</body>
<script src="js/vue.js"></script>
<script>
//全局注册组件
Vue.component('my-component',{
template: '#myComponent'
}) new Vue({
el: '#app'
}) </script>
</html>