我有一个页面,其中有一个标题,输入是一个搜索引擎,一个帖子列表和分页。我决定将此文件中的标题移动到单独的vue文件中的单独组件中。在我这样做之后,按标题搜索帖子停止了工作,我现在也无法添加帖子。我认为我需要将我的帖子导入到我新创建的组件的新文件中,但是如何操作。
And here is the code how it looked before my changes
Header.vue:
<template>
<div class="header">
<input type="text" v-model="search" class="header_input_search" placeholder="Search" />
<img src="src/assets/milk.png">
<div class="header_div_inputs">
<input type="text" v-model="createTitle" class="created"/>
<p><input type="text" v-model="createBody" class="createBody"/></p>
</div>
<button @click="addPost()" class="addPost">AddPost</button>
</div>
</template>
<script>
import axios from 'axios';
export default {
name: 'Pagination',
data () {
return {
search: '',
current: null,
posts: [],
createTitle: '',
createBody: '',
}
},
created(){
this.getData()
},
methods: {
getData() {
axios.get(`https://jsonplaceholder.typicode.com/posts`).then(response => {
this.posts = response.data
})
},
addPost() {
axios.post('http://jsonplaceholder.typicode.com/posts/', {
title: this.createTitle,
body: this.createBody
}).then((response) => {
this.posts.unshift(response.data)
})
},
}
}
</script>
App.vue:
<template>
<div id="app">
<header-self></header-self>
<router-view></router-view>
</div>
</template>
<script>
export default {
components: {
name: 'app',
}
}
</script>
我的帖子所在的文件:
<template>
<div class="app">
<ul>
<li v-for="(post, index) in paginatedData" class="post" :key="index">
<router-link :to="{ name: 'detail', params: {id: post.id, title: post.title, body: post.body} }">
<img src="src/assets/nature.jpg">
<p class="boldText"> {{ post.title }}</p>
</router-link>
<p> {{ post.body }}</p>
</li>
</ul>
<div class="allpagination">
<button type="button" @click="page -=1" v-if="page > 0" class="prev"><<</button>
<div class="pagin">
<button class="item"
v-for="n in evenPosts"
:key="n.id"
v-bind:class="{'selected': current === n.id}"
@click="page=n-1">{{ n }} </button>
</div>
<button type="button" @click="page +=1" class="next" v-if="page < evenPosts-1">>></button>
</div>
</div>
</template>
<script>
import axios from 'axios';
export default {
name: 'Pagination',
data () {
return {
search: '',
current: null,
page: 0,
posts: [],
createTitle: '',
createBody: '',
visiblePostID: '',
}
},
watch: {
counter: function(newValue, oldValue) {
this.getData()
}
},
created(){
this.getData()
},
computed: {
evenPosts: function(posts){
return Math.ceil(this.posts.length/6);
},
paginatedData() {
const start = this.page * 6;
const end = start + 6;
return this.posts.filter((post) => {
return post.title.match(this.search);
}).slice(start, end);
},
},
methods: {
getData() {
axios.get(`https://jsonplaceholder.typicode.com/posts`).then(response => {
this.posts = response.data
})
},
}
}
</script>
您的Pagination.vue组件中有一个依赖于搜索数据值的计算属性paginatedData,但该组件中未更新此值,因为您移动了将该值填充到该组件之外的搜索输入。
您现在需要做的是确保将更新的搜索值传递给Pagination.vue组件,以便计算属性检测到更改并计算新的分页数据值。
您现在遇到了在可能没有父/子关系的组件之间传递值的需要。
在您的场景中,我将考虑使用Vue文档中描述的一些Simple State Management处理此需求。
根据您的应用程序的规模,可能值得为州管理实施Vuex。
祝好运!