通过过滤器添加@click或路由器

时间:2018-03-27 11:20:39

标签: javascript vuejs2

我使用REST api获取帖子内容,删除了所有html标签。

{'post': {'Content': 'test content with #hashtag'}}

我使用filter和regex从内容创建主题标签。

<div v-html="$options.filters.customFilter(post.Content)"></div>
(...)
methods: 
   ale(tag) {
      alert('asdf')
   }
customFilter(val) {
      val = val.replace(/#(\S*)/g, '<a @click="ale(\'asdf\')" href="http://localhost:8080/tag/$1">$1</a>')
      return val
    }

问题是这个过滤器会创建html链接并强制整个网页重新加载(而不是路由器方式)

我尝试过@click但是vue没有解释它(在dom中是纯文本@click

如何从过滤器触发路由器或@click?

如果我不能有其他方法可以做到这一点?

修改 完整的代码是

<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
    <li v-bind:key="index" v-for="(post, index) in posts">
      <div v-html="$options.filters.customFilter(post.Content)"></div>
    </li>
  </div>
</template>

<script>
export default {
  name: 'Posta',
  data() {
    return {
      msg: 'Welcome to Your Vue.js App POST',
      posts: []
    }
  },
  methods: {
    ale() {
      alert('asdf')
    }
  },
  mounted() {
    this.posts = [{Content: 'test with #hashtag'}]
  },
  filters: {
    customFilter(val) {
      // ...
      val = val.replace(/#(\S*)/g, '<a @click="ale(\'asdf\')" href="http://localhost:8080/tag/$1">$1</a>')
      return val
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h1,
h2 {
  font-weight: normal;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  /*display: inline-block;*/
  margin: 0 10px;
}
a {
  color: #42b983;
}
</style>

2 个答案:

答案 0 :(得分:1)

而不是使用普通<a>标记 你必须使用<router-link :to="dynamicValue">

<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
    <li v-for="(post, index) in posts" v-bind:key="index">
      <router-link :to="getDynamicUrl(post.Content)">{{post.something}}</router-link>
    </li>
  </div>
</template>

<script>
export default {
  name: 'Posta',
  data() {
    return {
      msg: 'Welcome to Your Vue.js App POST',
      posts: []
    }
  },
  methods: {
    ale() {
      alert('asdf')
    },
    getDynamicUrl(val) {
       return val; //somethingWith val
    },
  },
  mounted() {
    this.posts = [{Content: 'test with #hashtag'}]
  },
}
</script>

答案 1 :(得分:0)

使用@click.prevent来阻止页面硬加载的默认操作:https://vuejs.org/v2/guide/events.html#Event-Modifiers

然后使用Vue Router push或其他一些程序化导航来更改vue路线:https://router.vuejs.org/en/essentials/navigation.html