I am new to VueJS and I am facing a challenge converting my VueJS project to use TypeScript. I have been trying to bind functions to certain variables in JavaScript, but I am struggling with accomplishing the same in TypeScript. Even though there are no errors reported in the developer tools, I am unable to get the route.query for VueJS to change.
My goal is to create a component similar to an auto search feature. I believe I might have used lodash incorrectly in TypeScript, but it's possible that my entire code needs correction. The code provided below showcases just one component, but there is another component, CharacterCard, that also monitors event changes on router.query and sends a request to the server to fetch data based on the user query. Are there better approaches or methods to implement this functionality?
If you require more information, please let me know.
<script>
import CharacterService from '../../services/characterService'
import CharacterCard from '../../components/_shared/CharacterCard.vue'
import Lodash from 'lodash'
export default {
components: {
CharacterCard
},
data () {
return {
dialog: false,
search: ''
}
},
methods: {
dialogAndSearchReset () {
this.search = ''
this.dialog = false
}
},
watch: {
// debounce of 700ms
search: Lodash.debounce(async function (value) {
// for route query
let route:any = {}
route = {
name: 'characters'
}
if (this.search !== '') {
route.query = {
search: this.search
}
}
// || this.$route.name === 'character'
if (this.$route.name === 'characters') {
this.$router.push(route)
}
}, 700),
'$route.query.search': {
immediate: true,
handler (value) {
this.search = value
}
},
$route (to, from) {
if (this.dialog === true && this.$route.name === 'character') {
this.dialogAndSearchReset()
}
}
}
}
</script>
My attempt:
<script lang="ts">
import { Component, Prop, Vue, Watch } from 'vue-property-decorator';
import CharacterSearchCard from './CharacterSearchCard.vue';
import _ from 'lodash';
@Component({
components: {
charactersearchcard: CharacterSearchCard,
},
})
export default class QuickSearch extends Vue {
// model for Dialog example
public customDialogModel: boolean = false;
public search: string = '';
// public quickSearch: any = this.$route.query.search || null; // the url search query
@Watch('search')
public searchCharacter(value: any) {
_.debounce(async () => {
// for route query
let route: any = {};
route = {
name: 'characters',
};
if (value !== '') {
route.query = {
search: value,
};
}
if (this.$route.name === 'characters') {
this.$router.push(route);
}
}, 700);
}
@Watch('$route.query.search', { immediate: true })
public searchHandler(value: any) {
this.search = value;
}
@Watch('$route')
public changeRoute(to, from) {
if (this.customDialogModel === true && this.$route.name === 'character') {
this.closeAndReset();
}
}
public closeAndReset() {
this.search = '';
this.customDialogModel = false;
}
public navigateTo(e) {
this.$router.push({
name: e,
});
}
}
</script>