移动端页面开发(2)

传值

父子组件传值并监听变化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// 父组件传值
<indexNews2 :search-key="this.key" :sort-key="this.active"></indexNews2>

// 子组件接值
export default {
props: {
searchKey: String,
sortKey: String,
}
}

// 子组件中调用参数
console.log('this.searchKey',this.searchKey,'this.sortKey',this.sortKey)

// 子组件监听参数变化
watch: {
searchKey(newValue, oldV) {
this.searchKey = newValue
console.log(this.searchKey, oldV)
this.getNewsList()
},
sortKey(newValue) {
this.sortKey = newValue
console.log(this.sortKey)
this.getNewsList()
}
}
1
2
3
4
5
6
7
8
<template>
// 传值,params 为隐式传值,query 会展示在地址栏中;name 为在router.js中配置的路由名
<router-link :to="{ name: 'newsItem', params: { newsId: newsItem.id }}">
</template>
<script>
// 接值
console.log(this.$route.params.newsId)
</script>

全局变量

在 src 文件夹下新建 global 目录,新建 global.vue 文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<template>
<div></div>
</template>

<script>
let username = ''
let newsSearchKey = ''
let newsSortKey = '关注'
let paperSearchKey = ''
let paperValue1 = '全部'
let paperValue2 = 'createTime'
export default{
username,
newsSearchKey,
newsSortKey,
paperSearchKey,
paperValue1,
paperValue2
}
</script>

在 main.js 中配置全局文件

1
2
3
4
5
//引用文件
import global_ from './global/global'

//挂载到Vue实例上面复制代码
Vue.prototype.GLOBAL = global_

axio调用接口

安装

1
2
npm install axios --save
bower install axios --save

main.js 中添加

1
2
3
4
import axios from 'axios'
import VueAxios from 'vue-axios'

Vue.use(VueAxios, axios);

使用 参考

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
this.axios.post(`http://xxx/user/register`, {
username: this.username,
password: this.password
}).then((res) => {
console.log(res);
if(res.data=="用户名已存在"){
console.log("用户名已存在")
Dialog({ message: '用户名已存在,请重新输入用户名' })
this.username = ''
this.password = ''
this.repassword = ''
}else if(res.data=="注册成功"){
console.log("注册成功")
Dialog.confirm({
title: '注册成功',
message: `${this.username},请您登录`,
}).then(() => {
this.$router.push({name: "login", params: {}})
})
.catch(() => {
})
}
}).catch((err) => {
console.log(err)
})

新闻页的值传递思路

新闻主界面为搜索导航和类别筛选的父组件+新闻列表的子组件构成。监听搜索框和筛选框的变化,将对应的值传给子组件,同时保存在全局变量中。因为每次进入某个新闻详情页面之后,需要返回新闻主界面,此时应保留用户上次的类别选择和搜索框内的值。