VUE解决锚点刷新问题

VUE解决锚点刷新问题

  // 子页面
  // 子页面按钮

<div style="padding-top: 20px;">
   <el-button type="danger" @click="jumpConsole3">Started</el-button>
  </div>

 // 调用父页面方法
methods: {
   jumpConsole3() {
      this.$parent.selfFun()
   }
 }
  // 父页面
  // 父页面锚点
  <a name="firstAnchor" id="firstAnchor"></a>

  // 父页面方法
    methods: {
    selfFun() {
      document.querySelector('#firstAnchor').scrollIntoView(true)
    },
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Vue 2中,可以使用`v-model`指令实现双向数据绑定。对于锚点(即页面上的锚点链接),可以通过绑定`window.location.hash`属性来实现双向绑定。 首先,在Vue实例中定义一个数据属性来存储当前的锚点值,比如`currentAnchor`。然后,在锚点链接中,使用`v-bind:href`指令将锚点值绑定到`window.location.hash`。同时,在锚点链接上监听`click`事件,当点击时更新`currentAnchor`的值。 下面是一个示例代码: ```html <div id="app"> <ul> <li v-for="anchor in anchors" :key="anchor"> <a :href="'#' + anchor" @click="updateAnchor(anchor)">{{ anchor }}</a> </li> </ul> <div> <input type="text" v-model="currentAnchor"> </div> </div> <script> new Vue({ el: "#app", data: { currentAnchor: '', anchors: ['anchor1', 'anchor2', 'anchor3'] }, mounted() { window.addEventListener('hashchange', this.updateCurrentAnchor); this.updateCurrentAnchor(); }, destroyed() { window.removeEventListener('hashchange', this.updateCurrentAnchor); }, methods: { updateAnchor(newAnchor) { this.currentAnchor = newAnchor; }, updateCurrentAnchor() { this.currentAnchor = window.location.hash.slice(1); } } }); </script> ``` 在上述代码中,`anchors`数组存储了需要添加锚点的值,通过`v-for`指令遍历生成锚点链接。当点击链接时,会调用`updateAnchor`方法更新`currentAnchor`的值。同时,通过监听`window`对象的`hashchange`事件,调用`updateCurrentAnchor`方法来更新`currentAnchor`的值。 这样,输入框中的值与页面上的锚点链接的值就实现了双向绑定。当修改输入框中的值时,锚点链接也会相应地更新;当点击锚点链接时,输入框中的值也会更新。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值