代码及注释:
- <div class="search-form">
- <input type="text" v-model="search" id="search" @input="handleInput" class="search" placeholder="词牌名 词句 词人"/>
- <ul class="suggestions" >
- <li v-for="item in showList" v-key="item.poetry_content"> //循环
- <span class="poet" v-html="highlight(item.poetry_content)">span> //v-html指令渲染
- <span class="title" v-html="highlight(item.title) + '-' + highlight(item.author)">span>
- li>
- ul>
- div>
- let vm = new Vue({
- el:'#app',
- // TODO:待补充代码
- data: {
- search: '',
- dataList: [],
- showList: []
- },
- mounted() {
- axios.get('./data.json').then(res => this.dataList = res.data) //获取数据
- },
- methods: {
- handleInput() {
- this.showList = this.dataList.filter(item => { //筛选含有关键字的数组
- for (const key in item) { //循环对象,将含有关键字的对象返回
- if(item[key].includes(this.search)) {
- return item
- }
- }
- })
- if (!this.search) { //当关键字为0,数组为0
- this.showList = []
- }
- },
- highlight(text) { //高光关键字
- return text.replaceAll(this.search, `${this.search}`)
- }
- }
- })
知识点:
1.v-html指令
它可以设置元素的 innerHTML 属性,从而实现 html 结构的解析和渲染
2.axios获取数据
axios.get(url).then(res => console.log(res))
3.for...in
该循环将迭代对象本身的所有可枚举属性
- for (variable in object)
- statement