单文件组件
命名规则如下所示:
------单个单词命名规则:------
方式一:temp.vue
方式二:Temp.vue 建议使用(可和vue开发者工具呼应)
------多个单词命名规则------
方式一:my-temp.vue
方式二:MyTemp.vue 建议使用(可和vue开发者工具呼应)
组件交互相关的代码暴露方式:
1.分别暴露:export const school = Vue.extend({})
2.统一暴露: export { school}
3.默认暴露: export default school 或 export default Vue.extend({}) 或 export default ({})
安装插件:vetur
注:在新建的.vue文件中输入vue回车后自动生成组件内容如下所示:
<template>
</template>
<script>
export default {
}
</script>
<style>
</style>
练习一下,组件书写内容:
student.vue
<!-- 组件的结构 -->
<template>
<div class="demo">
<h3>学校名称:{{stuName}}</h3>
<h3> 学校地址:{{ stuAddress }}</h3>
<button @click="showInfo">点我提示学校信息</button>
</div>
</template>
<!-- 组件交互相关的代码(数据、方法等) -->
<script>
//分别暴露
// export const school = Vue.extend({
// export default Vue.extend({
export default ({
name: 'Student',
data () {
return {
stuName: '心仪',
stuAddress: '西安/110号/希望小学',
}
},
methods: {
showInfo () {
alert(this.stuName + '/' + this.stuAddress)
}
}
})
// export { school} 统一暴露
// export default school 默认暴露
</script>
<!-- 组件的样式 -->
<style>
.demo {
background-color: burlywood;
}
</style>
school.vue
<!-- 组件的结构 -->
<template>
<div class="demo">
<h3>学校名称:{{schoolName}}</h3>
<h3> 学校地址:{{ schoolAddress }}</h3>
<button @click="showInfo">点我提示学校信息</button>
</div>
</template>
<!-- 组件交互相关的代码(数据、方法等) -->
<script>
//分别暴露
// export const school = Vue.extend({
// export default Vue.extend({
export default ({
name: 'School',
data () {
return {
schoolName: '希望小学',
schoolAddress: '西安/110号/希望小学',
}
},
methods: {
showInfo () {
alert(this.schoolName + '/' + this.schoolAddress)
}
}
})
// export { school} 统一暴露
// export default school 默认暴露
</script>
<!-- 组件的样式 -->
<style>
.demo {
background-color: burlywood;
}
</style>
App.vue
<template>
<div>
<School></School>
<Student></Student>
</div>
</template>
<script>
// 引入组件
import Student from './Student.vue';
import School from './School.vue';
export default {
name: 'App',
components: {
Student,
School
},
}
</script>
<style>
</style>
main.js
import App from "./App.vue";
//console.log(vm)
Vue.config.productionTip = false
const vm = new Vue({
el: '#root',
data: {
},
template: '<App></App>',//书写后,在index.html div中可不用显示 添加该标签,会自动添加
components: {
App
}
})
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>单文件组件语法练习</title>
</head>
<body>
<div id="root">
<App></App>
</div>
<!--
1.使用脚手架无需引入
2.不使用脚手架运行也会出错:
Uncaught SyntaxError: Cannot use import statement outside a module (at main.js:1:1)
<script type="text/javascript" src="../../Js/vue.js"></script>
<script type="text/javascript" src="./main.js"></script> -->
</body>
</html>
注:
<!--
1.使用脚手架无需引入
2.不使用脚手架运行也会出错:
Uncaught SyntaxError: Cannot use import statement outside a module (at main.js:1:1)
<script type="text/javascript" src="../../Js/vue.js"></script>
<script type="text/javascript" src="./main.js"></script> -->
博客内容主要用于日常学习记录,内容比较随意,如有问题,还需谅解!!!

浙公网安备 33010602011771号