VueJS 中的模型 URL 参数

hen*_*dry 5 javascript node.js vue.js vue-router

继续/sf/answers/4400192751/,我只想操作范围输入元素并使用该值更新 URL。

// https://github.com/vuejs/vue-router/blob/dev/examples/route-props/Hello.vue
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
    }
  }
});

const router = new VueRouter({
  // mode: 'history',
  routes: [
    { path: '*', component: Hello, props: true },
    { path: '/:agility', component: Hello, props: true },
  ]
})

new Vue({
  router,
  template: `
    <div id="app">
      <router-view></router-view>
    </div>
  `
}).$mount('#app')
Run Code Online (Sandbox Code Playgroud)
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>

<div id="app"></div>
Run Code Online (Sandbox Code Playgroud)

当未提供任何值时,我希望将默认值 25 附加到 URL,例如https://dabase.com/tips/web/2021/Minimal-VueJS-route-bind/#25

如果有一种更简单的方法可以在没有 vue-router 的情况下做到这一点,我洗耳恭听!

hen*_*dry 1

我在没有 vue-router 的情况下解决了它!

这里我们使用从 URL 哈希部分获得的数据来设置数据:

  created: function() {
    var hash = window.location.hash.substr(1)
    if (hash) {
        this.agility = hash
        }
  },
Run Code Online (Sandbox Code Playgroud)

当数据发生变化时,更新URL hash部分

   watch: {
    agility: function (newValue) {
      window.location.hash = newValue
    }
  },
Run Code Online (Sandbox Code Playgroud)