VueJS实现range输入同步URL参数及默认值补全,求无vue-router简化方案
方案一:修复现有vue-router实现
默认值未自动同步到URL的核心原因是初始化阶段没有主动将agility的取值同步到路由,只需要给Hello组件增加agility的监听即可:
var Hello = Vue.component('Hello', { template: ` <div> <h2 class="hello">Hello {{agility}} {{ $attrs }}</h2> <input min=0 max=100 v-model="agility" type="range"> </div> `, props: { agility: { type: Number, default: 25 } }, watch: { agility: { handler(val) { // 用replace避免拖动产生大量无效历史记录 this.$router.replace({ path: `/${val}` }) }, // 初始化就执行一次,自动把默认值同步到URL immediate: true } } }); // 路由配置注意匹配顺序,精确路由放前面 const router = new VueRouter({ routes: [ { path: '/:agility', component: Hello, props: true }, { path: '*', component: Hello, props: true }, ] })
修改后初始化如果URL没有参数,会自动追加默认值25到路径,拖动滑块时也会实时同步到URL。
方案二:无vue-router的简化实现
如果不需要多路由等复杂能力,仅需要同步值到URL hash,可以直接操作浏览器原生API,省略vue-router依赖,实现更轻量:
<script src="https://unpkg.com/vue/dist/vue.js"></script> <div id="app"> <h2 class="hello">Hello {{agility}}</h2> <input min=0 max=100 v-model="agility" type="range"> </div> <script> new Vue({ el: '#app', data() { return { agility: 25 } }, mounted() { // 初始化从hash取值 const hashVal = window.location.hash.slice(1) const numVal = Number(hashVal) if (!isNaN(numVal) && numVal >=0 && numVal <=100) { this.agility = numVal } // 监听hash变化更新滑块值 window.addEventListener('hashchange', () => { const hashVal = window.location.hash.slice(1) const numVal = Number(hashVal) if (!isNaN(numVal) && numVal >=0 && numVal <=100) { this.agility = numVal } }) }, watch: { // 滑块值变化更新hash agility(val) { window.location.hash = val } } }) </script>
该方案逻辑完全覆盖需求,不需要引入额外路由依赖,体积更小、逻辑更简洁。
内容的提问来源于stack exchange,提问作者hendry
相关产品推荐
相关产品推荐

