这次给大家带来有哪些vue组件的书写方法,使用vue组件的注意事项有哪些,下面就是实战案例,一起来看一下。
第一种使用script标签
<!doctype html>
<html>
<body>
<p id="app">
<my-component></my-component>
</p>
<-- 注意:使用<script>标签时,type指定为text/x-template,意在告诉浏览器这不是一段js脚本,浏览器在解析html文档时会忽略<script>标签内定义的内容。-->
<script type="text/x-template" id="mycomponent">//注意 type 和id。
<p>this is a component!</p>
</script>
</body>
<script src="js/vue.js"></script>
<script>
//全局注册组件
vue.component('my-component',{
template: '#mycomponent'
})
new vue({
el: '#app'
})
</script>
</html>
第二种使用template标签
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<p id="app">
<my-component></my-component>
</p>
<template id="mycomponent">
<p>this is a component!</p>
</template>
</body>
<script src="js/vue.js"></script>
<script>
vue.component('my-component',{
template: '#mycomponent'
})
new vue({
el: '#app'
})
</script>
</html>
第三种 单文件组件
这种方法常用在vue单页应用中。详情看官网:https://cn.vuejs.org/v2/guide/single-file-components.html
创建.vue后缀的文件,组件hello.vue,放到components文件夹中
<template>
<p class="hello">
<h1>{{ msg }}</h1>
</p>
</template>
<script>
export default {
name: 'hello',
data () {
return {
msg: '欢迎!'
}
}
}
</script>
app.vue
<!-- 展示模板 -->
<template>
<p id="app">
<img src="./assets/logo.png">
<hello></hello>
</p>
</template>
<script>
// 导入组件
import hello from './components/hello'
export default {
name: 'app',
components: {
hello
}
}
</script>
<!-- 样式代码 -->
<style>
#app {
font-family: 'avenir', helvetica, arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
相信看了本文案例你已经掌握了方法,更多精彩请关注其它相关文章!
推荐阅读:
新手必看的js实现异步方法
通过js获取json数据并加载的步骤详解
以上就是有哪些vue组件的书写方法的详细内容。