How to call a vue.js function on page load with vue3.0 and antd2.1.2 - vue.js

my vue project with vue3.0.0 and antd 2.1.2
there is a function "getScriptList", it can be executed automatically when placed in Component "mounted" with vue2.0
and I wonder how can it be automatically executed when loading the page with vue3.0?
I placed it in the component "onMounted" ,but it's useless.
this function "getScriptlist" can be executed mannul by
"
<a-button type="primary" #click="getScriptlist()">
ExecuteScriptList
"
my vue page test.vue:
<template>
<a-table
:row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
:columns="columns"
:data-source="dataSource"
bordered
>
<template #operation="{ record }">
<div>
<span >
<a #click="save(record.key)">Delete</a>
<a #click="edit(record.key)">Edit</a>
</span>
</div>
</template>
</a-table>
</template>
<script>
import { defineComponent, reactive, ref,computed,toRefs,onMounted } from 'vue';
import axios from 'axios';
const columns = [
{
title: 'name',
dataIndex: 'name',
},
{
title: 'timestamp',
dataIndex: 'timestamp',
},
{
title: 'location',
dataIndex: 'location',
},
{
title: 'operation',
dataIndex: 'operation',
slots: {
customRender: 'operation',
},
},
];
export default defineComponent({
setup() {
const dataSource = [];
......
function getScriptlist(){
axios.post(
"/api/script/getPid",
qs.stringify({
pid: 5,
}),
{
headers: { "Content-Type": "application/x-www-form-urlencoded" },
})
.then(response=>{
for( var i=0;i<response.data.length;i++)
{
dataSource.push(response.data[i])
}
})
.catch(function(error){
console.log(error);
});
}
onMounted(() =>
{
getScriptlist();
})
return {
getScriptlist,
dataSource,
columns,
.......
.......
};
},
});
</script>
<style>
</style>

Your component life cycle looks fine, but the dataSource should be defined as ref in order to be reactive:
const dataSource = ref([]);
then replace
for( var i=0;i<response.data.length;i++)
{
dataSource.push(response.data[i])
}
with
dataSource.value=response.data

Related

Default props value are not selected in vue3 options api

I created a select2 wrapper in vue3 with options API everything working fine but the problem is that when getting values from calling API it's not selected the default value in the select2 option. but when I created a static array of objects it does. I don't know why it's working when it comes from the API
Parent Component
Here you can I passed the static options array in options props and my selected value is 2 and it's selected in my Select2 component, but when passed formattedCompanies it's not which is the same format as the static options array then why is not selected any reason here..?
<template>
<Form #submitted="store()" :processing="submitting">
<div class="row">
<div class="col-lg-6">
<div class="form-group">
<label>Company Name</label>
<Select2
:options="options"
v-model="selected"
placeholder="Select Company"
/>
<ValidationError :errors="errors" error-key="name" />
</div>
</div>
</div>
</Form>
</template>
<script>
import Form from "#/components/Common/Form";
import Select2 from "#/components/Common/Select2";
export default {
components: {
Select2,
Form
},
data() {
return {
selected : 2,
companies : [],
options: [ // static array
{ id: 1, text: 'hello' },
{ id: 2, text: 'hello2' },
{ id: 3, text: 'hello3' },
{ id: 4, text: 'hello4' },
{ id: 5, text: 'hello5' },
],
}
},
mounted() {
this.getAllMedicineCompanies()
},
computed:{
formattedCompanies() {
let arr = [];
this.companies.forEach(item => {
arr.push({id: item.id, text: item.name})
});
return arr;
}
},
methods: {
getAllMedicineCompanies(){
axios.get('/api/get-data?provider=companies')
.then(({ data }) => {
this.companies = data
})
},
}
}
</script>
Select2 Component
Here is what my select2 component look like, did I do anything wrong here, please anybody help me
<template>
<select class="form-control">
<slot/>
</select>
</template>
<script>
export default {
name: "Select2",
props: {
options: {
type: [Array, Object],
required: true
},
modelValue: [String, Number],
placeholder: {
type: String,
default: "Search"
},
allowClear: {
type: Boolean,
default: true
},
},
mounted() {
const vm = this;
$(this.$el)
.select2({ // init select2
data: this.options,
placeholder: this.placeholder,
allowClear: this.allowClear
})
.val(this.modelValue)
.trigger("change")
.on("change", function () { // emit event on change.
vm.$emit("update:modelValue", this.value);
});
},
watch: {
modelValue(value) { // update value
$(this.$el)
.val(value)
.trigger("change");
},
options(options) { // update options
$(this.$el)
.empty()
.select2({data: options});
},
},
destroyed() {
$(this.$el)
.off()
.select2("destroy");
}
}
</script>
Probably when this Select2 mounted there is no companies. It is empty array after that it will make API call and it it populates options field and clear all options.
Make:
companies : null,
Change it to
<Select2
v-if="formattedCompanies"
:options="formattedCompanies"
v-model="selected"
placeholder="Select Company"
/>
It should be like this:
<template>
<Form #submitted="store()" :processing="submitting">
<div class="row">
<div class="col-lg-6">
<div class="form-group">
<label>Company Name</label>
<Select2
v-if="formattedCompanies"
:options="formattedCompanies"
v-model="selected"
placeholder="Select Company"
/>
<ValidationError :errors="errors" error-key="name" />
</div>
</div>
</div>
</Form>
</template>
<script>
import Form from "#/components/Common/Form";
import Select2 from "#/components/Common/Select2";
export default {
components: {
Select2,
Form
},
data() {
return {
selected : 2,
companies : null,
options: [ // static array
{ id: 1, text: 'hello' },
{ id: 2, text: 'hello2' },
{ id: 3, text: 'hello3' },
{ id: 4, text: 'hello4' },
{ id: 5, text: 'hello5' },
],
}
},
mounted() {
this.getAllMedicineCompanies()
},
computed:{
formattedCompanies() {
let arr = [];
this.companies.forEach(item => {
arr.push({id: item.id, text: item.name})
});
return arr;
}
},
methods: {
getAllMedicineCompanies(){
axios.get('/api/get-data?provider=companies')
.then(({ data }) => {
this.companies = data
})
},
}
}
</script>
The problem was that my parent component and Select2 component mounted at the same time that's why my computed value is not initialized so the selected value is not selected in the option,
problem solved by setTimeOut function in mounted like this
Select2 Component
<script>
mounted() {
const vm = this;
setTimeout(() => {
$(this.$el)
.select2({ // init select2
data: this.options,
placeholder: this.placeholder,
allowClear: this.allowClear
})
.val(this.modelValue)
.trigger("change")
.on("change", function () { // emit event on change.
vm.$emit("update:modelValue", this.value);
});
}, 500)
},
</script>

Vue.js: Child Component mutates state, parent displays property as undefined

I have a parent component that lists all the tasks:
<template>
<div class="tasks-wrapper">
<div class="tasks-header">
<h4>{{ $t('client.taskListingTitle') }}</h4>
<b-button variant="custom" #click="showAddTaskModal">{{ $t('client.addTask') }}</b-button>
</div>
<b-table
striped
hover
:items="tasks"
:fields="fields"
show-empty
:empty-text="$t('common.noResultsFound')">
</b-table>
<AddTaskModal />
</div>
</template>
<script>
import { mapActions, mapGetters } from 'vuex'
import AddTaskModal from '#/components/modals/AddTaskModal'
import moment from 'moment'
export default {
name: 'TaskListing',
components: {
AddTaskModal
},
data () {
return {
tasks: [],
fields: [
{ key: 'createdOn', label: this.$t('tasks.tableFields.date'), formatter: 'formatDate' },
{ key: 'domain', label: this.$t('tasks.tableFields.task') },
{ key: 'comment', label: this.$t('tasks.tableFields.comment') },
{ key: 'status', label: this.$t('tasks.tableFields.status') }
]
}
},
computed: {
...mapGetters('users', ['user'])
},
methods: {
...mapActions('tasks', ['fetchTasks']),
...mapActions('users', ['fetchUserById']),
formatDate: function (date) {
return moment.utc(date).local().format('DD.MM.YYYY HH:mm')
},
showAddTaskModal () {
this.$bvModal.show('addTaskModal')
}
},
async mounted () {
const currUserId = this.$router.history.current.params.id
if (this.user || this.user.userId !== currUserId) {
await this.fetchUserById(currUserId)
}
if (this.user.clientNumber !== null) {
const filters = { clientReferenceNumber: { value: this.user.clientNumber } }
this.tasks = await this.fetchTasks({ filters })
}
}
}
</script>
Inside this component there is a child which adds a task modal.
<template>
<b-modal
id="addTaskModal"
:title="$t('modals.addTask.title')"
hide-footer
#show="resetModal"
#hidden="resetModal"
>
<form ref="form" #submit.stop.prevent="handleSubmit">
<b-form-group
:invalid-feedback="$t('modals.requiredFields')">
<b-form-select
id="task-type-select"
:options="taskTypesOptions"
:state="taskTypeState"
v-model="taskType"
required
></b-form-select>
<b-form-textarea
id="add-task-input"
:placeholder="$t('modals.enterComment')"
rows="3"
max-rows="6"
v-model="comment"
:state="commentState"
required />
</b-form-group>
<b-button-group class="float-right">
<b-button variant="danger" #click="$bvModal.hide('addTaskModal')">{{ $t('common.cancel') }}</b-button>
<b-button #click="addTask">{{ $t('modals.addTask.sendMail') }}</b-button>
</b-button-group>
</form>
</b-modal>
</template>
<script>
import { mapActions, mapGetters } from 'vuex'
export default {
name: 'AddTaskModal',
data () {
return {
comment: '',
commentState: null,
taskTypesOptions: [
{ value: null, text: this.$t('modals.addTask.taskType') },
{ value: 'OnBoarding', text: 'Onboarding' },
{ value: 'Accounts', text: 'Accounts' },
{ value: 'TopUp', text: 'Topup' },
{ value: 'Overdraft', text: 'Overdraft' },
{ value: 'Aml', text: 'Aml' },
{ value: 'Transfers', text: 'Transfers' },
{ value: 'Consultation', text: 'Consultation' },
{ value: 'TechnicalSupport', text: 'TechnicalSupport' },
{ value: 'UnblockPin', text: 'UnblockPin' },
{ value: 'Other', text: 'Other' }
],
taskType: null,
taskTypeState: null
}
},
computed: {
...mapGetters('users', ['user']),
...mapGetters('tasks', ['tasks'])
},
methods: {
...mapActions('tasks', ['addNewTask', 'fetchTasks']),
...mapActions('users', ['fetchUserById']),
async addTask (bvModalEvt) {
bvModalEvt.preventDefault()
if (!this.checkFormValidity()) { return }
const currUserId = this.$router.history.current.params.id
if (this.user || this.user.userId !== currUserId) {
await this.fetchUserById(currUserId)
}
const data = {
clientPhone: this.user.phoneNumber,
comment: this.comment,
clientReferenceNumber: this.user.clientNumber,
domain: this.taskType
}
await this.addNewTask(data)
if (this.user.clientNumber !== null) {
const filters = { clientReferenceNumber: { value: this.user.clientNumber } }
this.tasks = await this.fetchTasks({ filters })
// this.tasks may be useless here
}
console.log(this.tasks)
this.$nextTick(() => { this.$bvModal.hide('addTaskModal') })
},
checkFormValidity () {
const valid = this.$refs.form.checkValidity()
this.commentState = valid
this.taskTypeState = valid
return valid
},
resetModal () {
this.comment = ''
this.commentState = null
this.taskTypeState = null
}
}
}
</script>
When I add a task I call getalltasks to mutate the store so all the tasks are added. Then I want to render them. They are rendered but the property createdOn on the last task is InvalidDate and when I console log it is undefined.
The reason I need to call gettasks again in the modal is that the response on adding a task does not return the property createdOn. I do not want to set it on the front-end, I want to get it from the database.
I logged the store and all the tasks are added to the store.
Why is my parent component not rendering this particular createdOn property?
If I refresh the page everything is rendering fine.
If you add anything into a list of items that are displayed by v-for, you have to set a unique key. Based on your explanation, I assume that your key is the index and when you add a new item, you mess with the current indexes. Keys must be unique and unmutateable. What you need to do is to create a unique id for each element.
{
id: Math.floor(Math.random() * 10000000)
}
When you create a new task, use the same code to generate a new id, and use id as key. If this doesn't help, share your d-table and related vuex code too.

ag-Grid does not support .vue component as cellRenderer?

So I have this itemlist.vue file
<div>
<div>
<ag-table
style=" height: 650px;"
class="ag-theme-balham"
:column-defs="columnDefs"
:row-data="rowData"
/>
</div>
</div>
</template>
<script>
import AgTable from "../components/AgTable";
import editRenderer from "../components/AgGridRenderers/editDeleteRenderer.vue";
export default {
components: {
AgTable
},
data: () => ({
users: [],
columnDefs: null,
rowData: null,
editR: editRenderer
}),
mounted () {
this.columnDefs = [
{ headerName: "Name", field: "name", sortable: true, filter: true },
{ headerName: "e-Mail", field: "email", sortable: true, filter: true },
{ headerName: "Contact", field: "contact", sortable: true, filter: true },
{ headerName: "Contact", field: "contact", sortable: true, filter: true, cellRenderer: editRenderer }
];
this.rowData = [
{ name: "Robin Sharma", email: "robin#sharma.com", contact: 8508035076 },
{ name: "Amish Tripathi", email: "amish#tripathi.com", contact: 9250035054 },
{ name: "Zig Ziglar", email: "zig#ziglar.com", contact: 9206635030 },
{ name: "Paulo Coelho", email: "paolo#coelho.com", contact: 7288012335 }
];
},
methods: {
loadUsers () {
// console.log("Loading Users from api.");
}
}
};
</script>
And index.vue file for Ag grid table as
<template>
<div>
<ag-grid-vue
style=" height: 650px;"
class="ag-theme-balham"
:column-defs="_props.columnDefs"
:row-data="_props.rowData"
:framework-components="frameworkComponents"
/>
</div>
</template>
<script>
import "ag-grid-community/dist/styles/ag-grid.css";
import "ag-grid-community/dist/styles/ag-theme-balham.css";
import { AgGridVue } from "ag-grid-vue";
import editRenderer from "../AgGridRenderers/editDeleteRenderer.vue";
export default {
components: {
AgGridVue
},
props: [
"column-defs", "row-data"
],
data: () => ({
frameworkComponents: {
editRenderer
}
}),
mounted () {
console.log(this._props.columnDefs, this._props.rowData);
}
};
</script>
And editrenderer.vue file as:
<template>
<div>
<span>
<button #click="sayHi"> Edit Item </button>
</span>
</div>
</template>
<script>
export default {
created () {
console.log("Hello from Edit");
},
methods: {
sayHi () {
alert("Hi");
}
}
};
</script>
And all I am getting in the DOM is empty edit-renderer tags
Doesn't AgGrid support cellRenderers in Vue Js?
In the end the imported component appears as a vue component in the Dom if used separately as a common Dom element. Does that mean we explicitly have to compile it somehow? I also tried using setTimeOut before initializing columnDefs and rowData where AgTable is used. but still it doesn't show anything in the table.
Ok, so what I did was add some missing properties to ag-grid-vue element such as grid-options, context and grid-ready, and add refresh function to the renderer component, and convert all related components from simple "export default{" to "export default Vue.extends({".
I think this problem was resolved.
Though, I am getting 'this is undefined' error now.
Ag-grid should clarify which parameters are compulsory other than rowData and colDefs with their purpose.

Display Boolean on Vuetify dataTable

I made a data table with vue vuetify and I fetch my data from my api server.
In my table, everything is display except boolean.
Can you help me to see clearer
Table component
<template>
<v-data-table
:headers="headers"
:items="fixture"
:items-per-page="5"
class="elevation-10"
>
</v-data-table>
</template>
<script>
export default {
name: 'my_fixtures',
props: ['fixture'],
data () {
return {
headers: [
{ text: 'name',value: 'name'},
{ text: 'State', value: 'on' },
{ text: 'Group', value: 'group' },
{ text: 'Recipe', value: 'recipe' },
{ text: 'start', value: 'startDate' },
{ text: 'end', value: 'endDate' },
{ text: 'Action', value: 'action' },
],
items: this.fixtures
}
}
}
</script>
In the object that I receive , the key 'on' is a Boolean.
I have all display , but nothing in the 'on' column
and this is what I do with props
<template>
<v-container>
<my_fixtures v-bind:fixture="fixtures"></my_fixtures>
<router-view></router-view>
</v-container>
</template>
<script>
import my_fixtures from "./greenhouse/fixtures";
export default {
name: "my_client",
data: function (){
return {fixtures: []}
},
components: {my_fixtures},
mounted() {
http.get('fixture/client')
.then(result => {
this.fixtures = result;
})
.catch(error => {
console.error(error);
});
}
}
</script>
Process and print data using methods.
try this.
<td class="text-xs-right">{{ computedOn(props.fixture.on) }}</td>
export default {
methods: {
computedOn (value) {
return String(value)
}
}
}
UPDATE
Modifying original data due to vuetify bug
https://github.com/vuetifyjs/vuetify/issues/8554
export default {
mounted() {
http.get('fixture/client')
.then(result => {
this.fixtures = result.map(value => {
value.on = String(value.on)
})
})
.catch(error => {
console.error(error);
});
}
}

Getting bootstrap vue pagination to play with REST api

Trying to get Bootstrap Vue to play with a REST api that returns data for one page and the total number of records (based on this):
<template>
</div>
<b-pagination
v-on:change="onPageChange"
:total-rows="totalRows"
:per-page="perPage"
v-model="currentPage" />
<b-table responsive striped hover show-empty
stacked="md"
:items="items"
:fields="fields"
:current-page="currentPage"
:per-page="perPage"
:filter="filter"
:sort-by.sync="sortBy"
:sort-desc.sync="sortDesc"
:sort-direction="sortDirection"
#filtered="onFiltered">
</b-table>
</div>
</template>
<script>
...
export default {
name: 'TableList',
data() {
return {
module: null,
title: 'Table',
items: [],
fields: [],
errors: [],
currentPage: 1,
perPage: 15,
totalRows: 0,
pageOptions: [ 5, 10, 15 ],
sortBy: null,
sortDesc: false,
sortDirection: 'asc',
filter: null,
}
},
created() {
...
this.fetch();
},
methods: {
fetch() {
var me = this;
var requestParams = {
page: this.currentPage,
per_page: this.perPage
};
if(this.sortBy) {
requestParams = Object.assign({ sort_by: this.sortBy }, requestParams);
}
Rest('GET', '/table/' + this.table, requestParams, this.$root.user.token)
.then(response => {
me.items = response.data[1]
me.totalRows = response.data[0].total_entries
})
.catch(error => {
this.errors.push('Error: ' + error.response.status + ': ' + error.response.statusText)
})
.finally(() => {
//alert('turn off loader!');
});
}
}
</script>
This Vue works if I fetch the entire table. However, when I use the REST api to return one page at a time, the number of pages is calculated to be 1, and the forward and end links are inactive. Thus, I am unable to trigger a request for e.g. page 2.
The REST api correctly returns the total number of rows in the table, and the number of rows requested, but Bootstrap Vue does not appear to be watching/reacting to changes to this.totalRows.
What have I missed?
You need to set the per-page prop to 0 on the b-table component to disable the local pagination and allow b-pagination to handle the data. Here's an example:
new Vue({
el: '#app',
data() {
return {
items: [],
fields: [{
key: 'postId',
label: 'Post ID'
},
{
key: 'id',
label: 'ID'
},
{
key: 'name',
label: 'Name'
},
{
key: 'email',
label: 'Email'
},
{
key: 'body',
label: 'Body'
}
],
currentPage: 0,
perPage: 10,
totalItems: 0
}
},
mounted() {
this.fetchData().catch(error => {
console.error(error)
})
},
methods: {
async fetchData() {
this.items = await fetch(`https://jsonplaceholder.typicode.com/comments?_page=${this.currentPage}&_limit=${this.perPage}`)
.then(res => {
this.totalItems = parseInt(res.headers.get('x-total-count'), 10)
return res.json()
})
.then(items => items)
}
},
watch: {
currentPage: {
handler: function(value) {
this.fetchData().catch(error => {
console.error(error)
})
}
}
}
})
<link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap/dist/css/bootstrap.min.css" />
<link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap-vue#latest/dist/bootstrap-vue.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.22/vue.js"></script>
<script src="//unpkg.com/babel-polyfill#latest/dist/polyfill.min.js"></script>
<script src="//unpkg.com/bootstrap-vue#latest/dist/bootstrap-vue.js"></script>
<div id="app">
<b-table show-empty :items="items" :fields="fields" :current-page="currentPage" :per-page="0"></b-table>
<b-pagination size="md" :total-rows="totalItems" v-model="currentPage" :per-page="perPage"></b-pagination>
</div>
You can also disabled local pagination in the table, so that your items provider becomes responsible for controlling the pagination.