[英]Watch Value In Vue.js 3, Equivalent In Pinia?
I have a checkbox list of domain tlds, such as com,.net, io, etc. I also have a search text input, where I can drill down the list of 500 or so domains to a smaller amount.我有一个域 tld 的复选框列表,例如 com、.net、io 等。我还有一个搜索文本输入,我可以在其中向下钻取 500 个左右域的列表到更小的数量。 For example, if I start to type co in to my search text input, I will get back results that match co, such as co, com, com.au, etc. I am using Laravel and Vue.js 3 to achieve this with a watcher.
例如,如果我开始在我的搜索文本输入中输入 co,我将得到与 co 匹配的结果,例如 co、com、com.au 等。我使用 Laravel 和 Vue.js 3 通过观察者实现此目的. It works beautifully.
它工作得很漂亮。 How can an achieve the same within a Pinia store?
如何在 Pinia 商店内实现相同的目标?
Here is my code currently:这是我目前的代码:
watch: {
'filters.searchedTlds': function(after, before) {
this.fetchsearchedTlds();
}
},
This is inside my vue component.这是在我的 vue 组件中。
Next is the code to fetch searched tlds:接下来是获取搜索到的顶级域名的代码:
fetchsearchedTlds() {
self = this;
axios.get('/fetch-checked-tlds', { params: { searchedTlds: self.filters.searchedTlds } })
.then(function (response) {
self.filters.tlds = response.data.tlds;
console.log(response.data.tlds);
})
.catch(function (error) {
console.log(error);
})
.then(function () {
// always executed
});
},
And finally, the code inside my Laravel controller:最后,我的 Laravel controller 中的代码:
public function fetchCheckedTlds(Request $request)
{
$data['tlds'] = Tld::where('tld', 'LIKE','%'.$request->input('searchedTlds').'%')->pluck('tld');
return response()->json($data);
}
I am converting my code to use a Pinia store and I am stuck on how to convert my vue component watcher to Pinia?我正在将我的代码转换为使用 Pinia 商店,但我对如何将我的 vue 组件观察器转换为 Pinia 感到困惑?
Many thanks in advance.提前谢谢了。
To watch a pinia
status, you may watch a computed
attribute based on pinia
or use watch getter要查看
pinia
状态,您可以查看基于pinia
的computed
属性或使用watch getter
Your pinia
may look like the one below.您的
pinia
可能如下所示。
~/store/filters.js ~/store/filters.js
export const useFilters = defineStore('filters', {
state: () => {
return {
_filters: {},
};
},
getters: {
filters: state => state._filters,
},
...
}
In where you want to watch在你想看的地方
<script setup>
import { computed, watch } from 'vue';
import { useFilters } from '~/store/filters.js';
const filters = useFilters();
// watch a computed attributes instead
const searchedTlds = computed(() => {
return filters.filters?.searchedTlds || '';
});
watch(
searchedTlds,
(newValue, oldValue) {
fetchsearchedTlds();
}
);
// or use watch getter
watch(
() => {
return filters.filters?.searchedTlds || '';
},
(newValue, oldValue) {
fetchsearchedTlds();
}
);
</script>
The first parameter of watch()
can be a single ref or a getter function, or an array of getter functions, for more details, please view the Watch Source Types . watch()
的第一个参数可以是一个单独的 ref 或一个 getter function,也可以是一个 getter 函数数组,更多细节请查看Watch Source Types 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.