本文涉及3个内容:
1.vue 组件:
目录结构:
源码分析如下:
爱吃什么水果? app 实例
爱吃什么水果? app2 实例
爱吃什么水果?
组件没有在任何实例中,所以不显示 「组件一定要挂载到某个 Vue 实例中,否则不会生效」
界面显示字段:
组件一定要挂载到某个 Vue 实例中, 这里更新代码如下:
定义一i个vue 实例,将组件挂载到实例上去。组件构造器和vue 实例非常相似。
这里构建了如下构造器:
var todolist = Vue.extend({
template:'
效果可由vue debug 视图看到。
2.vue props 属性较为复杂:
2.1 考虑方法:
vue 中的方法可以看到vue 有不同的浏览器去解析。控制台显示。
考虑2:vue propertes:
定义1个组件:
// 定义一个组件
var myComponent = Vue.extend({
// 定义 props 就是一些默认值
props: {
message:"",
mydata:{},
//样式 ,如果这里使用驼峰标识 ,则在标签中使用就要使用 name-style 传递
nameStyle:{},
// 这里规定传递过来的数据必须是数字,否则后台会报警告
age: Number,
clickme:{
type:Function
}
},
data(){
return {
// 可以在数据里面将 props 值赋给 data 值,然后就可以修改这个值,但是原始的 props 中的值是修改不了的
msg:this.message
}
},
template: ''+
'{{ message }}--{{msg}}'+
''+
'{{ mydata.username}} {{this.age}}'+
''+
''+
' '
})
由全局组件向后台传递:
Vue.component('mycomponent', myComponent)
var vm2 = new Vue({
el:'#app2',
methods: {
show(msg) {
// return () =>{
if(msg){
alert('带回调的参数是:'+msg)
}else {
alert('没有带参数回调')
}
// console.log(this,arguments)
// }
}
}
})
考虑3,生命周期:
在如下demo 中演示了vue 生命周期限制:
beforeCreate(){
console.group("%c%s","color:red",'beforeCreate--实例创建前状态')
console.log("%c%s","color:blue","el :"+this.$el)
console.log("%c%s","color:blue","data :"+this.$data)
console.log("%c%s","color:blue","msg :"+this.msg)
},
created() {
console.group("%c%s","color:red",'created--实例创建完成状态')
console.log("%c%s","color:blue","el :"+this.$el)
console.log("%c%s","color:blue","data :"+this.$data)
console.log("%c%s","color:blue","msg :"+this.msg)
},
beforeMount() {
console.group("%c%s","color:red",'beforeMount--挂载之前的状态')
console.log("%c%s","color:blue","el :"+this.$el)
console.log(this.$el);
console.log("%c%s","color:blue","data :"+this.$data)
console.log("%c%s","color:blue","msg :"+this.msg)
console.log("%s%o","document.getElementById('container'): ",document.getElementById('container'))
},
效果如图所示:
考虑4: 页面跳转路由:
页面跳转路由:
h5 路由方式:
function home() {
// 添加到历史记录栈中
history.pushState({name:'home',id:1},null,"?page=home#index")
showCard('home')
};
function message() {
history.pushState({name:'message',id:2},null,"?page=message#haha")
showCard('message')
}
function mine(){
history.pushState({
id:3,
name:'mine'
},null,"?name=tigerchain&&sex=man")
showCard('mine')
}
通过监听h5 的路由方式执行,
内置全局路由实现:
// 创建 router 实例
const router = new VueRouter({
routes // 就相当于是 routes:routes
})
// 创建 Vue 并挂载,并且注册路由,这样 container 下都有路由功能
var vm = new Vue({
el:'#container',
router
})
申明路由规则:
// 声明路由规则
const routes = [
//给一个默认的路由,默认显示 Main 组件
{
path:'/',component:Main
},
{
path:'/main',component:Main
},
{
path:'/message',component:Message
},
{
path:'/mine/:id',component:Mine
}
]
然后定义3个组件相互完成。