一、通过url传递参数
url是一种描述文件在计算机网络中位置的方式。在uniapp中,可以通过url传递参数。在web开发中,可以通过query string来传递参数。在uniapp中有两种方式来进行url传参:路由跳转和h5页面跳转:
1.路由跳转
uniapp中提供了一些路由相关的api,其中,uni.navigateto和uni.redirectto这两个api可以在跳转时携带参数。在跳转时,可以将参数以对象的形式传递给url,并以query string(查询字符串)的形式来表示。如下所示:
uni.navigateto({ url: '/pages/detail/detail?id=123&name=apple'})
在被跳转的页面中,可以通过this.$route.query对象访问到传递的参数。如下所示:
export default { mounted() { console.log(this.$route.query.id) // 123 console.log(this.$route.query.name) // 'apple' }}
需要注意的是,通过路由跳转传递的参数会保存在导航栏的历史记录中,因此,可以通过返回操作返回上一个页面,并携带参数。
2.h5页面跳转
在uniapp中,可以通过location.search来获取url中的查询字符串和参数,例如:
var url = window.location.search; // ?id=123&name=applevar obj = {};if (url.indexof(?) != -1) { url = url.substr(1); // id=123&name=apple var arr = url.split(&); for(var i = 0; i < arr.length; i++) { var tmp = arr[i].split(=); obj[tmp[0]] = tmp[1]; }}console.log(obj.id); // 123console.log(obj.name); // 'apple'
需要注意的是,在h5页面中跳转时,需要手动对url进行处理。
二、通过vuex传递参数
在uniapp中,可以使用vuex进行状态管理,因此,我们也可以通过vuex来进行参数传递。
在页面中创建store在每个页面中,我们需要首先创建一个store来进行参数传递。如下所示:
import vue from 'vue'import vuex from 'vuex'vue.use(vuex)const store = new vuex.store({ state: { id: '', name: '' }, mutations: { set_id(state, id) { state.id = id }, set_name (state, name) { state.name = name } }})export default store
在页面中引入store,如下所示:
import store from '@/store/index'
在页面中传递参数在需要传递参数的页面中,可以通过提交mutation来将参数传递到store中。如下所示:
export default { methods: { handleclick() { this.$store.commit('set_id', '123') this.$store.commit('set_name', 'apple') } }}
在提交mutation后,store中的对应state就被更新了。
在页面中获取参数在需要获取参数的页面中,可以通过$store.state对象来获取store中存储的参数。如下所示:
export default { mounted() { console.log(this.$store.state.id) // 123 console.log(this.$store.state.name) // 'apple' }}
需要注意的是,使用vuex进行参数传递需要引入vuex,并且需要在每个页面中都创建store。
总结
在uniapp中,我们可以通过url和vuex两种方式来进行参数传递。对于简单的参数传递,我们可以选择使用url传参,并且可以根据具体情况选择路由跳转或h5页面跳转。对于复杂的场景,我们可以选择使用vuex来进行参数传递,但需要注意在每个页面中创建store。无论使用哪种方式,都需要根据实际需求进行选择。
以上就是uniapp如何传递参数的详细内容。
