vue3App.vue文件介绍
<template>
<div class="app">
<router-view />
</div>
</template>
<script>
export default {
name: 'App'
}
</script>
<style>
...
</style>
vue3app.vue文件是Vue3框架开发手机App的核心文件之一。如上代码所示,vue3app.vue文件由template
、script
和style
三个部分组成。
template
部分中,div.app
是整个手机App的根元素,router-view
是App的路由视图,具体的页面内容会在不同的路由视图展示。
script
部分中,export default
用于导出此文件的内容,name: 'App'
是组件名,可以在App.vue模板中使用此组件。由于在.vue
文件中需先写template
部分,再写script
部分,因此在script
部分中可以直接引用template
部分的元素和标签。
style
部分用于书写该文件的样式表。
在vue3app.vue文件中实现国际化
<template>
<div class="app">
{{ $t('greeting') }}
</div>
</template>
<script>
export default {
name: 'App',
created() {
this.$i18n.locale = 'zh-CN'
}
}
</script>
<style>
...
</style>
在.vue
文件中实现国际化,需要使用Vue I18n库。如上代码所示,在template
部分的div.app
中,通过{{ $t('greeting') }}
来显示在该国际化环境下的greeting
字段。
在script
部分中,通过created
生命周期钩子,将当前的国际化语言设置为zh-CN
。Vue I18n库会根据当前设定的国际化语言来选择相应的翻译文本,从而实现国际化。
在vue3app.vue文件中引用组件
<template>
<div class="app">
<header></header>
<router-view />
<footer></footer>
</div>
</template>
<script>
import Header from '@/components/Header.vue'
import Footer from '@/components/Footer.vue'
export default {
name: 'App',
components: {
Header,
Footer
}
}
</script>
<style>
...
</style>
在.vue
文件中引用组件通常需要import
语句,如上代码所示,在script
部分中,我们通过import
语句来引入Header
和Footer
组件。
为了能够在template
部分中使用Header
和Footer
组件,我们需要在export default
部分中,添加components
属性,并为其赋值。在上述代码中,我们为Header
和Footer
组件分别指定了Header
和Footer
的名称,以便我们在template
部分中像使用router-view
一样,直接使用<header></header>
、<footer></footer>
标签。
在vue3app.vue文件中引用插件
<template>
<div class="app">
<router-view />
</div>
</template>
<script>
import VueAwesomeSwiper from 'vue-awesome-swiper'
export default {
name: 'App',
mounted() {
Vue.use(VueAwesomeSwiper)
}
}
</script>
<style>
...
</style>
vue-awesome-swiper
是一个Vue.js轮播插件。如上代码所示,我们需要在script
部分中使用import
语句将它引入。在mounted
生命周期钩子中,将VueAwesomeSwiper
通过Vue.use()
方法使用起来。
注意:从Vue3.0开始,Vue.use()
方法的参数只能传入插件对象而不能直接传入Vue.use(VueAwesomeSwiper)
,因为插件必须以对象形式提供。解决方法是将vue-awesome-swiper
作为一个插件对象导入,如:
import Vue from 'vue'
import VueAwesomeSwiper from 'vue-awesome-swiper'
// import style (>= Swiper 6.x)
import 'swiper/swiper-bundle.css'
Vue.use(VueAwesomeSwiper)
Vue.config.productionTip = false
new Vue({
...
})
在vue3app.vue文件中添加自定义指令
<template>
<div class="app">
<div v-mydire="color"></div>
</div>
</template>
<script>
export default {
name: 'App',
directives: {
mydire: {
bind(el, binding, vnode) {
el.style.color = binding.value
}
}
}
}
</script>
<style>
...
</style>
在Vue.js中,自定义指令是一种允许你在DOM元素上添加新行为的功能。如上代码所示,在template
部分中,我们为一个div
元素添加了v-mydire
指令,它将绑定一个color
属性的值。
在script
部分中,我们通过directives
属性为自定义指令起个名字,例如上述代码中的mydire
。在mydire
中,我们使用bind()
方法,为该指令绑定了一个函数。在这个函数中,我们通过el.style.color = binding.value
来为当前的这个div
元素设置文字颜色。