@Niksak

Код, работающий в watch, не работает в computed во vue?

Вот такие дела, код работает в watch, не работает в computed:((

<script>
//Импорт компонентов "по старинке"
import PostForm from "@/components/PostForm.vue";
import PostList from "@/components/PostList.vue";
import MyModal from "./components/UI/MyModal.vue";
import axios from "axios";
//По дефолту экспортируем всегда объект, который и является компонентом
  export default{
    components:{
    PostForm,
    PostList,
    MyModal
},
    data(){ //Здесь объявляем данные
      return{//Возвращаем нужные данные
        posts: [],
        modalVisible: false,
        isLoading: false,
        selectedSort: '',
        sortOptions:[
          {value:'title', name:'По названию'},
          {value:'body', name:'По описанию'}
        ],
        searchPost:''
      }
    },
    methods: {//Здесь методы, функции
      createPost(post){ //Этот метод вызывается из компонента дочернего
        this.posts.push(post);
        this.modalVisible = false;
      },
      removePost(post){
        this.posts = this.posts.filter(p => p.id !== post.id);
      },
      showModal(){
        this.modalVisible = true;
      },
      async fetchPosts(){
        try{
          this.isLoading = true;
          setTimeout(async () => {
            const response = await axios.get("https://jsonplaceholder.typicode.com/posts?_limit=10");
            this.posts = response.data;
            this.isLoading = false;
          }, 1000)
 
        }catch(err){
          alert("Ашыбка")
        }
      }
      // inputTitle(evt){
      //   this.title = evt.target.value;
      // },
      // inputBody(evt){
      //   this.body = evt.target.value;
      // },
    },
    mounted(){
      this.fetchPosts();
    },

    computed:{
      sortedPosts(){
        return [...this.posts].sort((post1, post2) => {
          return post1[this.selectedSort]?.localeCompare(post2[this.selectedSort]);
        })
      }
    },

    watch: {
      // selectedSort(newValue){
      //   this.posts.sort((post1, post2) => {
      //     return post1[newValue]?.localeCompare(post2[this.newValue]);
      //   })
      // },
      // searchedPosts(){
      //   return this.selectedSort.filter(post=> post.title.includes(this.searchPost));
      // }
    }
  }
</script>
  • Вопрос задан
  • 95 просмотров
Пригласить эксперта
Ответы на вопрос 2
yarkov
@yarkov Куратор тега Vue.js
Помог ответ? Отметь решением.
return post1[newValue]?.localeCompare(post2[this.newValue]);

Всё так и задумано?
Ответ написан
@alubochkin
Может я что не внимательно смотрю но что в this.selectedSort лежит не пустая ли строка
computed:{
sortedPosts(){
return [...this.posts].sort((post1, post2) => {
return post1[this.selectedSort]?.localeCompare(post2[this.selectedSort]);
})
}
},
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы